package cn.fl.system.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.user.facade.system.condition.SysResourceQueryCondition;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysRoleResRService;
import cn.fl.system.vo.SysRoleResRVO;
import net.sf.json.JSONObject;

/**
 * @Description: 系统角色-资源关系表 控制层
 */
@Controller
@RequestMapping("/system/sysRoleResR")
public class SysRoleResRController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SysRoleResRController.class);

	/**
	 * SysRoleResR 服务层BEAN
	 */
	@Autowired
	private ISysRoleResRService sysRoleResRService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载角色资源关系列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("system/sysRoleResR/sysSysRoleResRList");
		
		// 角色类型
		List<KeyValueVO> roleTypCdList = this.sysRoleResRService.searchResTypCdList();
		if(roleTypCdList!=null){
			view.addObject("roleTypCdList", roleTypCdList);
		}
		List<KeyValueVO> isVisCdList = this.sysRoleResRService.searchIsVisCdList();
		if(isVisCdList!=null){
			view.addObject("isVisCdList", isVisCdList);
		}
		return view;
	}
	/**
	 * 通过资源名称模糊得到资源树
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getByResNm.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getByResNm(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String resNm = request.getParameter("resNm");
		String[] resIdArr = request.getParameterValues("RESOURCE_IDs[]");
		BaseLogUtils.info(logger, "getByResNm", "加载资源树.",CurrentThreadContext.getCurrentUserName());
		List<String> resIdList = new ArrayList<String>();
		if(resIdArr!=null&&resIdArr.length>0){
			Collections.addAll(resIdList, resIdArr);
		}
		List<Long> ids = new ArrayList<Long>();
		if(CollectionUtils.isNotEmpty(resIdList)){
			
			for (String idStr : resIdList) {
				ids.add(Long.valueOf(idStr));
			}
		}
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		SysResourceQueryCondition condition = new SysResourceQueryCondition();
		if(StringUtils.isNotBlank(resNm)){
			
			condition.setResNm(resNm);
		}
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
		
		try {
			
			JSONObject jsonObject = this.sysRoleResRService.searchResRByResRIdList(ids, condition);
			if(jsonObject==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getByResNm", "获取资源数据不存在.", CurrentThreadContext.getCurrentUserName());
			}else{
				BaseLogUtils.info(logger, "getByResNm", "加载资源树成功.", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(jsonObject);
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getByResNm", "获取资源数据失败.ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getByResNm", "获取资源数据失败,系统错误.ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}


	

	/**
	 * 通过角色id得到资源树
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getByRoleId.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getByRoleId(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String roleIdStr = request.getParameter("roleId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		Long roleId = null;
		if(StringUtils.isEmpty(roleIdStr)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_AUTH_ROLE_ID_NOT_EMPTY);
			BaseLogUtils.info(logger, "getByRoleId", "通过角色ID获取资源树数据,角色ID参数为空！", CurrentThreadContext.getCurrentUserName());
			return result;
		}
			
		try {
			roleId =Long.valueOf(roleIdStr);
			JSONObject jsonObject = this.sysRoleResRService.searchResRByRoleId(roleId, null);
			if(jsonObject==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getByRoleId", "通过角色ID获取资源树数据不存在,roleId:"+roleIdStr, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(jsonObject);
			BaseLogUtils.info(logger, "getByRoleId", "通过角色ID获取资源树数据成功,roleId:"+roleIdStr, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getByRoleId", "通过角色ID获取资源树数据失败,roleId:"+roleIdStr+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getByRoleId", "通过角色ID获取资源树数据失败,系统错误.roleId:"+roleIdStr+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	/**
	 * 通过角色id得到资源树初始化数据
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getTreeByRoleId.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getTreeByRoleId(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String roleIdStr = request.getParameter("roleId");
		Long roleId = null;
		if(StringUtils.isNotEmpty(roleIdStr)){
			roleId =Long.valueOf(roleIdStr);
		}
		
		try {
			JSONObject jsonObject = this.sysRoleResRService.searchResRByRoleId(roleId, null);
			return jsonObject.get("data");
		}catch(Exception ex) {
			BaseLogUtils.error(logger, "getTreeByRoleId", "通过角色ID获取资源树初始化数据失败,系统错误.roleId:"+roleIdStr+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return null;
	}

	/**
	 * 新增 角色授权
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String roleIdStr = request.getParameter("roleId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		Long roleId =null;
		List<SysRoleResRVO> sysRoleResRVOList = new ArrayList<SysRoleResRVO>();
		if(StringUtils.isBlank(roleIdStr)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_AUTH_ROLE_ID_NOT_EMPTY);
			BaseLogUtils.info(logger, "add", "角色授权,角色ID参数为空！", CurrentThreadContext.getCurrentUserName());
			return result;
		}else{
			roleId =Long.valueOf(roleIdStr);
		}
		
		String[] resIdArr = request.getParameterValues("resIdArr[]");
		List<String> resIdList = new ArrayList<String>();
		if(resIdArr!=null&&resIdArr.length>0){
			Collections.addAll(resIdList, resIdArr);
		}
		if(CollectionUtils.isNotEmpty(resIdList)){
			
			for (String string : resIdList) {
				Long resId = Long.valueOf(string);
				SysRoleResRVO sysRoleResRVO = new SysRoleResRVO();
				sysRoleResRVO.setRoleId(roleId);
				sysRoleResRVO.setResId(resId);
				sysRoleResRVOList.add(sysRoleResRVO);
			}
		}
		try {
			
			boolean addAuth = this.sysRoleResRService.addAuth(roleId,sysRoleResRVOList);
			if(!addAuth){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
				BaseLogUtils.info(logger, "add", "角色授权失败.roleId:"+roleIdStr+".resIds:"+JSON.toJSONString(resIdArr), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "add", "角色授权成功.roleId:"+roleIdStr+".resIds:"+JSON.toJSONString(resIdArr), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "角色授权失败.roleId:"+roleIdStr+".resIds:"+JSON.toJSONString(resIdArr)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "角色授权失败,系统错误..roleId:"+roleIdStr+".resIds:"+JSON.toJSONString(resIdArr)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	/**
	 * 权限继承
	 */
	@RequestMapping(value = "/extendResR.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object extendResR(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String curRoleId = request.getParameter("curRoleId");
		String extRoleId = request.getParameter("extRoleId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(curRoleId)||StringUtils.isEmpty(extRoleId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_AUTH_ROLE_ID_NOT_EMPTY);
			BaseLogUtils.info(logger, "extendResR", "权限继承失败,角色ID参数为空.curRoleId:"+curRoleId+".extRoleId"+extRoleId, CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			boolean success = this.sysRoleResRService.modifyExtendsResR(Long.valueOf(curRoleId), Long.valueOf(extRoleId));
			
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
				BaseLogUtils.info(logger, "extendResR", "权限继承失败.curRoleId:"+curRoleId+".extRoleId"+extRoleId, CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "extendResR", "权限继承成功.curRoleId:"+curRoleId+".extRoleId"+extRoleId, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "extendResR", "权限继承失败.curRoleId:"+curRoleId+".extRoleId"+extRoleId+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "extendResR", "权限继承失败,系统错误.curRoleId:"+curRoleId+".extRoleId"+extRoleId+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
		
		
	}

	
}

